package com.fesine.produce;

import java.util.LinkedList;

/**
 * @description: 同步块await和notify方法
 * @author: Fesine
 * @createTime:2017/7/28 23:17
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/7/28 23:17
 */
public class Storage {
    private final int MAX_SIZE = 100;
    private LinkedList<Object> list = new LinkedList<>();

    /**
     * 生产num个商品
     * @param num
     */
    public void produce(int num) {
        //同步代码块
        synchronized (list) {
            //仓库剩余容量不够
            while (list.size() + num > MAX_SIZE) {
                System.out.println(Thread.currentThread().getName()+"\t[要生产的商品数量]" + num + "\t[库存量]" + list.size()
                        + "\t暂时不能执行生产任务");
                try {
                    //线程等待
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            //可以生产出num个商品
            for (int i = 0; i < num; i++) {
                list.add(new Object());
            }
            System.out.println(Thread.currentThread().getName() +"\t[已经生产出商品数量]" + num + "\t[库存量]" + list.size());
            //通知其他线程执行
            list.notifyAll();
        }
    }

    public void consume(int num) {
        synchronized (list) {
            //库存不足，线程等待
            while (list.size() < num) {
                System.out.println(Thread.currentThread().getName() +"\t[要消费的商品数量]" + num + "\t[库存量]" + list.size()
                        + "\t暂时不能执行消费任务");
                try {
                    //线程等待
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            //满足条件，则消费商品
            for (int i = 1; i <= num; ++i) {
                list.remove();
            }
            System.out.println(Thread.currentThread().getName() +"\t[已经消费商品数量]" + num + "\t[库存量]" + list.size());
            //通知其他线程执行
            list.notifyAll();
        }
    }

    public int getMAX_SIZE() {
        return MAX_SIZE;
    }

    public LinkedList<Object> getList() {
        return list;
    }

    public void setList(LinkedList<Object> list) {
        this.list = list;
    }
}
